package com.fjj.cs.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjj.cs.mapper.ScannerMapper;
import com.fjj.cs.vo.request.AddUserByScanner;
import com.fjj.cs.vo.request.PageRequestVO;
import com.fjj.cs.vo.request.TestVo;
import com.fjj.cs.util.HttpUtil;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class TestService {

    @Resource
    ScannerMapper scannerMapper;

    public static void main(String[] args) {
        // PDF文件路径
        String filePath = "D:\\obscene\\blue\\cs\\src\\main\\resources\\pdf\\asd.pdf";
        ITesseract tesseract = new Tesseract();
        tesseract.setDatapath("C:\\Program Files\\Tesseract-OCR\\tessdata"); // 设置 tessdata 文件夹的路径
        // 设置语言（例如中文和英文）
        tesseract.setLanguage("chi_sim");

        List<String> list = new ArrayList<>();
        list.add("-l chi_sim+eng");
        list.add("-psm 6");
        list.add("-oem 3");

        // 设置配置参数
        tesseract.setConfigs(list);
        try {
            String text = tesseract.doOCR(new File(filePath));
            text = text.replaceAll(" ", "");
            // 打印PDF内容（可选，调试用）
             System.out.println(text);

            // 提取标题（假设标题格式为《合同标题》）
            String title = extractTitle(text);
            System.out.println("标题: " + title);

            // 提取甲方和乙方
            List<String> parties = extractParties(text);
            System.out.println("甲方: " + parties.get(0));
            System.out.println("乙方: " + parties.get(1));



        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 提取合同标题（假设标题以《》包围）
    private static String extractTitle(String text) {
        // 匹配多个换行符（\r\n 或 \n），并获取第一行的文字
        Pattern titlePattern = Pattern.compile("^(\\s*.*?)\\s*(\\r?\\n|$)");
        Matcher matcher = titlePattern.matcher(text);
        if (matcher.find()) {
            return matcher.group(1).trim().replace(" ", "");  // 去除前后空格
        }
        return "未找到标题";
    }

    // 提取甲方和乙方（假设甲方和乙方使用“甲方”和“乙方”关键字）
    private static List<String> extractParties(String text) {
        List<String> parties = new ArrayList<>(); // 甲方和乙方

        // 提取甲方
        Pattern partyPattern = Pattern.compile("甲\\s*方.*?[:：]\\s*([^\\s]+)");
        Matcher partyMatcher = partyPattern.matcher(text);
        if (partyMatcher.find()) {
            parties.add(partyMatcher.group(1).trim());
        } else {
            parties.add("未找到甲方");
        }

        // 提取乙方
        partyPattern = Pattern.compile("乙\\s*方.*?[:：]\\s*([^\\s]+)");
        partyMatcher = partyPattern.matcher(text);
        if (partyMatcher.find()) {
            parties.add(partyMatcher.group(1).trim().replace(" ", ""));
        } else {
            parties.add("未找到乙方");
        }

        partyPattern = Pattern.compile("(?:时\\s*间.*?|日\\s*期.*?)[:：]\\s*([^\\s]+)");
        partyMatcher = partyPattern.matcher(text);
        if (partyMatcher.find()) {
            System.out.println(partyMatcher.group(1).trim().replace(" ", "")); ;
        }

        return parties;
    }

    /**
     * @param testVo
     */
    public void addUserByLinux(TestVo testVo) {
        InputStream in = null;
        InputStream errorStream = null;
        try {
            File file = new File("/home/fjj"); // 根目录作为工作目录
            Process pro = Runtime.getRuntime().exec("./test.sh " + testVo.getUserName() + " " + testVo.getPassword(), null, file);

            // 等待脚本执行完成
            pro.waitFor();

            // 读取标准输出流
            in = pro.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in));
            String result;
            while ((result = read.readLine()) != null) {
                System.out.println(result);
            }

            // 读取错误输出流
            errorStream = pro.getErrorStream();
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
            String errorLine;
            while ((errorLine = errorReader.readLine()) != null) {
                // 打印错误信息
                System.err.println(errorLine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();  // 关闭标准输出流
                }
                if (errorStream != null) {
                    errorStream.close();  // 关闭错误输出流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加用户到扫描仪
     */
    public void addUserScanner(AddUserByScanner addUserByScanner) {
        // 获取loginCookie
        String loginCookie = getLoginCookie();

        // 获取操作的序号
        String operationNumber = getOperationNumber(loginCookie);

        // 获取新增操作的token
        String inputSetUpToken = getInputSetUpToken(loginCookie);

        // 进行新增
        addUserByScanner(addUserByScanner, loginCookie, inputSetUpToken, operationNumber);
    }

    /**
     * 添加用户到扫描仪
     *
     * @param addUserByScanner 添加对象请求参数
     * @param loginCookie      cookie
     * @param inputSetUpToken  编辑的token
     * @param operationNumber  编辑的序号
     */
    public void addUserByScanner(AddUserByScanner addUserByScanner, String loginCookie, String inputSetUpToken, String operationNumber) {
        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/x-www-form-urlencoded");
        headers.put("cookie", loginCookie);

        // 请求的地址
        String url = "https://192.168.11.8/PRESENTATION/ADVANCED/CONTACTS/TOP";

        // 请求参数
        Map<String, String> body = new HashMap<>();
        body.put("NUMBER", operationNumber);
        body.put("INPUTT_NAME", "wangxing");
        body.put("INPUTT_INDEX", "DISPLAY");
        body.put("INPUTD_TYPE", "FTP");
        body.put("INPUTC_USEREGULARY", "OFF");
        body.put("INPUTD_SECURECONNECTION", "FTP");
        body.put("INPUTT_FOLDERPATHFTP", "192.168.10.10/");
        body.put("INPUTT_FOLDERPATHSMB", "192.168.10.10/");
        body.put("INPUTD_WEBDAVSECURECONNECTION", "HTTP");
        body.put("INPUTT_FOLDERPATHWEBDAV", "192.168.10.10/");
        body.put("INPUTT_FOLDERUSERNAME", "xiaolizi");
        body.put("INPUTT_FOLDERPASSWORD", "123456");
        body.put("INPUTD_CONNECTMODE", "ACTIVE");
        body.put("INPUTT_PORTNUM", "21");
        body.put("INPUTR_PROXYSERVER", "NOTUSE");
        body.put("page", "1");
        body.put("listnum", "50");
        body.put("pageGroup", "0");
        body.put("listnumGroup", "0");
        body.put("EXEID", "SET");
        body.put("INPUTT_SETUPTOKEN", inputSetUpToken);

        HttpResponse httpResponse = null;
        try {
            // 发送请求
            httpResponse = HttpUtil.doPost(url, null, null, headers, new HashMap<>(), body);

            // 获取响应体内容
            String responseEntityBody = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);

            // 解析 HTML
            Document doc = Jsoup.parse(responseEntityBody);

            // 获取 class 为 "warning red" 的 div 元素
            Element div = doc.select("div.warning.red").first();

            // 获取 div 中的文本内容
            if (!Objects.isNull(div)) {
                String text = div.text();
                if (!text.contains("设置完成")) {
                    throw new RuntimeException("设置失败,原因如下:" + text);
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取操作的序号
     *
     * @param loginCookie
     * @return
     */
    private String getOperationNumber(String loginCookie) {

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/x-www-form-urlencoded");
        headers.put("cookie", loginCookie);

        // 请求的地址
        String url = "https://192.168.11.8/PRESENTATION/ADVANCED/CONTACTS/TOP";

        // 请求参数
        Map<String, String> body = new HashMap<>();
        body.put("page", "1");
        body.put("listnum", "50");
        body.put("EXEID", "DISPLAY");

        HttpResponse httpResponse = null;

        try {
            // 发送请求
            httpResponse = HttpUtil.doPost(url, null, null, headers, new HashMap<>(), body);

            // 获取响应体内容
            String responseEntityBody = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);

            // 解析 HTML 内容
            Document doc = Jsoup.parse(responseEntityBody);
            // 查找表格中的所有行
            Elements rows = doc.select("tbody#common_table_body tr");

            //  遍历每一行
            for (Element row : rows) {
                Elements tds = row.select("td");
                // 如果小于6行跳过
                if (tds.size() < 6) continue;

                // 获取第5行并去掉前后空白字符
                Element targetTd = tds.get(5);
                String targetContent = targetTd.html().trim();

                // 判断该目标列的内容是否为 &nbsp;
                if (targetContent.equals("&nbsp;")) {
                    return tds.get(1).text();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        throw new RuntimeException("没有找打符合条件的序号");
    }

    /**
     * 获取新增操作的token
     *
     * @param loginCookie
     * @return
     */
    private String getInputSetUpToken(String loginCookie) {
        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/x-www-form-urlencoded");
        headers.put("cookie", loginCookie);

        // 请求的地址
        String url = "https://192.168.11.8/PRESENTATION/ADVANCED/CONTACTS/EDIT";

        // 请求参数
        Map<String, String> body = new HashMap<>();
        body.put("page", "1");
        body.put("listnum", "50");
        body.put("NUMBER", "25");

        HttpResponse httpResponse = null;
        try {
            // 发送请求
            httpResponse = HttpUtil.doPost(url, null, null, headers, new HashMap<>(), body);

            // 获取响应体内容
            String responseEntityBody = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
            // 解析HTML内容
            Document doc = Jsoup.parse(responseEntityBody);

            // 查找包含name="INPUTT_SETUPTOKEN"的<input>标签
            Element inputElement = doc.select("input[name=INPUTT_SETUPTOKEN]").first();

            // 如果找到该input元素，提取value属性值
            if (!Objects.isNull(inputElement)) {
                return inputElement.val();
            } else {
                throw new RuntimeException("没有找到token");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 调用扫描仪登录接口并获取响应的html文件
     */
    public String getLoginCookie() {
        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/x-www-form-urlencoded");

        // 请求的地址
        String url = "https://192.168.11.8/PRESENTATION/ADVANCED/PASSWORD/SET";

        // 请求参数
        Map<String, String> body = new HashMap<>();
        body.put("INPUTT_USERNAME", "fjj");
        body.put("access", "https");
        body.put("INPUTT_PASSWORD", "fjj123456");
        body.put("INPUTT_ACCSESSMETHOD", "0");


        HttpResponse httpResponse = null;
        try {
            // 发送请求
            httpResponse = HttpUtil.doPost(url, null, null, headers, new HashMap<>(), body);

            // 获取响应中的cookie
            Header[] cookies = httpResponse.getHeaders("Set-Cookie");

            // 打印每个cookie
            for (Header cookie : cookies) {
                String cookieValue = cookie.getValue();

                // 正则表达式提取session ID
                Pattern pattern = Pattern.compile("EPSON_COOKIE_SESSION=session&([a-zA-Z0-9\\-]+)");
                Matcher matcher = pattern.matcher(cookieValue);

                if (matcher.find()) {
                    return "EPSON_COOKIE_SESSION=session&" + matcher.group(1);  // 提取的完整session ID
                } else {
                    throw new RuntimeException("没有获取到cookie");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        throw new RuntimeException("没有找打符合条件的token");
    }


    public IPage<TestVo> testVoIPage(PageRequestVO pageRequestVO) {
        return scannerMapper.selectScannerPage(new Page<TestVo>(pageRequestVO.getCurrentPage(), pageRequestVO.getPageSize()), pageRequestVO);
    }
}
